local M = {}

-- Default configuration
local default_config = {
  rules = {
    { keyword = "最后更新:", date_format = "%Y年%m月%d日 %H:%M:%S" },
    { keyword = "LastUpdate:", date_format = "%Y-%m-%d %H:%M:%S" },
    { keyword = "updated:", date_format = "%Y-%m-%d %H:%M:%S" },
  },
  header_lines = 20,
  stop_on_first_match = true,
}

-- Global configuration variable
M.config = {}

-- Merge user config with default config
local function merge_config(user_config)
  local config = vim.tbl_deep_extend("force", {}, default_config, user_config or {})
  return config
end

-- Setup function
function M.setup(user_config)
  M.config = merge_config(user_config)

  -- Set up automatic update on BufWritePre
  local augroup = vim.api.nvim_create_augroup("AutoUpdateHeader", { clear = true })
  vim.api.nvim_create_autocmd("BufWritePre", {
    group = augroup,
    pattern = "*",
    callback = function()
      M.auto_update()
    end,
  })
end

-- Get current time with specified format
local function get_current_time(date_format)
  return os.date(date_format)
end

-- Get time pattern for matching
local function get_time_pattern(date_format)
  -- Convert date format to regex pattern
  local pattern = date_format
  pattern = pattern:gsub("%%%%", "%%") -- Escape %%
  pattern = pattern:gsub("%%Y", "%%d+") -- Year
  pattern = pattern:gsub("%%m", "%%d+") -- Month
  pattern = pattern:gsub("%%d", "%%d+") -- Day
  pattern = pattern:gsub("%%H", "%%d+") -- Hour
  pattern = pattern:gsub("%%M", "%%d+") -- Minute
  pattern = pattern:gsub("%%S", "%%d+") -- Second
  pattern = pattern:gsub("年", "年?") -- Chinese year (optional)
  pattern = pattern:gsub("月", "月?") -- Chinese month (optional)
  pattern = pattern:gsub("日", "日?") -- Chinese day (optional)
  pattern = pattern:gsub("时", "时?") -- Chinese hour (optional)
  pattern = pattern:gsub("分", "分?") -- Chinese minute (optional)
  pattern = pattern:gsub("秒", "秒?") -- Chinese second (optional)
  return pattern
end

-- Update header time for a specific rule
local function update_header_time_for_rule(bufnr, rule, header_lines)
  local lines = vim.api.nvim_buf_get_lines(bufnr, 0, header_lines, false)
  local keyword = rule.keyword
  local date_format = rule.date_format
  local time_pattern = get_time_pattern(date_format)
  local current_time = get_current_time(date_format)

  local updated = false

  for i, line in ipairs(lines) do
    if line:find(keyword, 1, true) then -- Plain text search for keyword
      -- Create a pattern to match the keyword and any existing time
      local escaped_keyword = keyword:gsub("([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
      local full_pattern = "^%s*(" .. escaped_keyword .. ")%s*(.*)"

      -- Try to match with the full pattern
      local _, _, prefix, existing_content = line:find(full_pattern)

      if prefix then
        -- Replace the line with updated time
        local new_line = prefix .. " " .. current_time
        vim.api.nvim_buf_set_lines(bufnr, i - 1, i, false, { new_line })
        updated = true
        if M.config.stop_on_first_match then
          break
        end
      end
    end
  end

  return updated
end

-- Main update function
function M.update()
  -- Check if we're in a normal buffer (not a special buffer)
  local bufnr = vim.api.nvim_get_current_buf()
  local buf_name = vim.api.nvim_buf_get_name(bufnr)

  -- Skip special buffers (empty, quickfix, etc.)
  if buf_name == "" or vim.api.nvim_buf_get_option(bufnr, "buftype") ~= "" then
    return
  end

  local config = M.config

  -- Get lines from buffer header
  local header_lines = config.header_lines

  -- Process rules
  local updated = false
  for _, rule in ipairs(config.rules) do
    updated = update_header_time_for_rule(bufnr, rule, header_lines)
    if updated and config.stop_on_first_match then
      break
    end
  end

  return updated
end

-- Auto update function that will be called on BufWritePre
function M.auto_update()
  M.update()
end

return M
